<?php
namespace frontend\models;

use common\models\RelationPostTags;
use yii\base\Model;
use common\models\Posts;
use yii\db\Query;
use yii\web\NotFoundHttpException;

class PostForm extends Model
{
    public $id;
    public $title;
    public $content;
    public $label_img;
    public $cat_id;
    public $tags;

    public $_lastError = "";

    /*场景*/
    const SCENARIOS_CREATE = 'create';
    const SCENARIOS_UPDATE = 'update';
    const EVENT_AFTER_CREATE = 'eventAfterCreate';
    const EVENT_AFTER_UPATE = 'eventAfterUpdate';

    public function scenarios()
    {
        $scenarios = [//场景更新字段
            self::SCENARIOS_CREATE => ['title','content','label_img','cat_id','tags'],
            self::SCENARIOS_UPDATE => ['title','content','label_img','cat_id','tags'],
        ];

        return array_merge(parent::scenarios(),$scenarios);
    }

    public function rules()
    {
        return [
            [['id', 'title', 'content', 'cat_id'], 'required'],
            [['id', 'cat_id'], 'integer'],
            ['title', 'string','min'=>4,'max'=>50],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => '编码',
            'title' => '标题',
            'content' => '内容',
            'label_img' => '标签图',
            'tag' => '标签',
            'cat_id' => '分类'
        ];
    }

    public function create(){
        //事务启用
        $transaction = \Yii::$app->db->beginTransaction();

        try {
            $model = new Posts();
            $model->setAttributes($this->attributes);
            $model->summary = $this->_getSummary();
            $model->user_id = \Yii::$app->user->identity->id;
            $model->user_name = \Yii::$app->user->identity->username;
            $model->is_valid = Posts::IS_VALID;
            $model->created_at = time();
            $model->updated_at = time();

            if(!$model->save()){
                throw new \Exception('文章保存失败');
            }

            $this -> id = $model -> id;

            //完成后调用事件
            $date = array_merge($this->attributes(),$model->getAttributes(),['tags' => $this->tags]);
            $this->_eventAfterCreate($date);
            $transaction->commit();
            return true;
        } catch (\Exception $e) {
            $transaction -> rollBack();
            $this -> _lastError = $e->getMessage();
            return false;
        }

    }

    protected function _getSummary($s = 0,$e = 90 ,$char ='utf-8'){
        if(empty($this->content)){ return null; }

        return (mb_substr(str_replace('&nbsp;','',strip_tags($this->content)),$s,$e));
    }

    /*事件处理*/
    protected function _eventAfterCreate($date){
        //添加事件
        $this->on(self::EVENT_AFTER_CREATE,[$this,'_eventAddTag'],$date);

        //触发事件
        $this->trigger(self::EVENT_AFTER_CREATE);
    }

    /*添加标签*/
    public function _eventAddTag($event){
        $tag = new TagForm();
        $tag -> tags = $event->data['tags'];
        $tagids = $tag->saveTags();

        //删除所有原有标签再加过
        RelationPostTags::deleteAll(['post_id' => $event->data['id']]);

        //批量保存
        if(!empty($tagids)){
            foreach($tagids as $k=>$id){
                $row[$k]['post_id'] = $this->id;
                $row[$k]['tag_id'] = $id;
            }

            $res = (new Query())->createCommand()
                ->batchInsert(RelationPostTags::tableName(),['post_id','tag_id'],$row)->execute();
        }

        if(!$res){ throw new \Exception('标签保存失败'); }

    }

    /*获取列表*/
    public function getPostList()
    {
        $list = Posts::find()->where(['is_valid' => 1])->all();

        if(!$list){ throw new \Exception('暂无更多信息'); }

        $data = [];
        foreach ($list as $info){
            $data[] = [
                'title' => $info->title,'summary' => $info->summary,'label_img' => $info->label_img,
                'id' => $info->id,'user_name' => $info->user_name,'created_at' => $info->created_at
            ];
        }

        return $data;
    }

    /*获取详情*/
    public function getViewById($id)
    {
        $data = Posts::find()->with('relate.tag')->where(['id' => $id])->asArray()->one();

        if(!$data){
            throw new NotFoundHttpException('文章不存在');
        }

        //处理标签格式
        $data['tags'] = [];
        if(isset($data['relate']) && !empty($data['relate'])){
            foreach ($data['relate'] as $list){
                $data['tags'][] = $list['tag']['tag_name'];
            }
        }

        unset($data['relate']);
        return $data;
    }

}